package com.yang.inventorymanagement.controllerview.products;

import com.yang.inventorymanagement.comment.TableComponent;
import com.yang.inventorymanagement.controllerview.suppliers.SupplierAddManageSwing;
import com.yang.inventorymanagement.pojo.Products;
import com.yang.inventorymanagement.service.InventoryService;
import com.yang.inventorymanagement.service.ProductsService;
import com.yang.inventorymanagement.utils.SessionUtils;
import com.yang.inventorymanagement.utils.SpringContextUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;


@Lazy
@Scope("prototype")
@Component("ProductsManageSwing")
/**
 * 商品管理界面
 */
public class ProductsManageSwing extends JPanel {
    private JTextField productsSelectField;

    private JTextField suppliersIdUpdate;
    private JTextField productsId;
    private JTextField productsNumber;
    private JTextField productsName;

    private TableComponent table;
    private JButton flushBtn;

    private TableComponent suppliersTable;
    private JPanel contentPane;

    // 表格数据
    private Object[] columnNames = {"商品编号", "商品名称", "商品库存"};
    private Object[][] rowData;

    //商品service
    private ProductsService productsService = SpringContextUtils.getBean(ProductsService.class);
    //库存service
    private InventoryService inventoryService = SpringContextUtils.getBean(InventoryService.class);


    public ProductsManageSwing() {
        setBounds(0, 0, 1165, 730);
        setLayout(null);
        JButton productsAddBtn = new JButton("添加商品");
        // 添加供应商
        productsAddBtn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                ProductsAddSwing frame = SpringContextUtils.getBean("ProductsAddSwing", ProductsAddSwing.class);
                frame.setVisible(true);
                updateProductsList(0, null);
            }

        });
        productsAddBtn.setBounds(10, 10, 93, 23);
        add(productsAddBtn);


        /**
         * 刷新按钮
         */
        flushBtn = new JButton("刷新");
        flushBtn.setBounds(127, 10, 80, 23);

        // 刷新
        flushBtn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.out.println("刷新");
                updateProductsList(0, null);
            }
        });
        add(flushBtn);


        /**
         * 搜索框，搜索按钮
         */
        productsSelectField = new JTextField();
        productsSelectField.setBounds(236, 11, 389, 22);
        add(productsSelectField);
        productsSelectField.setColumns(10);

        JButton searchBtn = new JButton("商品名称搜索");
        searchBtn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                //获取搜索框信息
                String input = productsSelectField.getText();
                //数据校验
                if (input == null || "".equals(input.trim())) {
                    JOptionPane.showMessageDialog(null, "输入不能为空", "提示", JOptionPane.ERROR_MESSAGE);
                    return;
                }
                //更新用户列表
                updateProductsList(1, input);
            }
        });
        searchBtn.setBounds(635, 10, 121, 23);
        add(searchBtn);
        JPanel suppliersListPanel = new JPanel();
        suppliersListPanel.setBorder(BorderFactory.createTitledBorder("商品库存列表"));
        suppliersListPanel.setBounds(10, 54, 746, 661);
        add(suppliersListPanel);
        // 设置表格数据
        rowData = productsService.getAllproducts();
        // 创建一个表格，指定 所有行数据 和 表头
        table = new TableComponent(rowData, columnNames);
        suppliersListPanel.add(table.getTableHeader());                        // 添加表头
        suppliersListPanel.setLayout(new BorderLayout(5, 5));
        JScrollPane scrollPane = new JScrollPane(table);                // 将表格添加到滚动面板中
        suppliersListPanel.add(scrollPane);
        /**
         * 商品库存展示
         */
        // 商品信息管理界面
        JPanel productsMsgPanel = new JPanel();
        productsMsgPanel.setBorder(BorderFactory.createTitledBorder("商品库存管理"));
        // 设置 GridBagLayout 布局管理器
        productsMsgPanel.setBounds(766, 54, 389, 661);
        add(productsMsgPanel);
        productsMsgPanel.setLayout(null);

        JLabel lblid = new JLabel("商品编号");
        lblid.setBounds(37, 31, 54, 15);
        productsMsgPanel.add(lblid);

        productsId = new JTextField();
        productsId.setEnabled(false);
        productsId.setBounds(101, 28, 200, 21);
        productsMsgPanel.add(productsId);
        productsId.setColumns(10);

        JLabel label_3 = new JLabel("商品名称");
        label_3.setBounds(37, 72, 54, 15);
        productsMsgPanel.add(label_3);
        productsName = new JTextField();
        productsName.setEnabled(false);
        productsName.setBounds(101, 69, 200, 21);
        productsMsgPanel.add(productsName);

        JLabel label = new JLabel("商品库存");
        label.setBounds(37, 103, 54, 15);
        productsMsgPanel.add(label);

        productsNumber = new JTextField();
        productsNumber.setEnabled(false);
        productsNumber.setBounds(101, 110, 200, 21);
        productsMsgPanel.add(productsNumber);
        productsNumber.setColumns(10);


        /**
         * 库存修改按钮以及操作，
         */
        JButton productsNumberButton = new JButton("库存管理");
        productsNumberButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {

                if (productsId.getText() == null || "".equals(productsId.getText())) {
                    JOptionPane.showMessageDialog(null, "未选中商品", "提示", JOptionPane.ERROR_MESSAGE);
                    return;
                }
                String text = productsId.getText();
                SessionUtils.getSession().put("productsId", productsId.getText());
                ProductsNumberManageSwing frame = SpringContextUtils.getBean("ProductsNumberManageSwing", ProductsNumberManageSwing.class);

                // ProductsNumberManageSwing frame =  SpringContextUtils.getBean("ProductsNumberManageSwing",ProductsNumberManageSwing.class);
                frame.setVisible(true);
            }
        });
        productsNumberButton.setBounds(37, 607, 93, 23);
        productsMsgPanel.add(productsNumberButton);

        /**
         * 商品供应商管理
         * 一个商品多个供应商，供应商的crud
         */
        JButton productsSuppliersButton = new JButton("新增供应商");
        productsSuppliersButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (productsId.getText() == null || "".equals(productsId.getText())) {
                    JOptionPane.showMessageDialog(null, "未选中商品", "提示", JOptionPane.ERROR_MESSAGE);
                    return;
                }
                SessionUtils.getSession().put("productsId", productsId.getText());
                ProductsSuppliersSwing frame = SpringContextUtils.getBean("ProductsSuppliersSwing", ProductsSuppliersSwing.class);
                // ProductsSuppliersSwing frame = (ProductsSuppliersSwing) SpringContextUtils.getBean("ProductsSuppliersSwing");
                frame.setVisible(true);
            }
        });
        productsSuppliersButton.setBounds(271, 607, 93, 23);
        productsMsgPanel.add(productsSuppliersButton);


        // 设置表格监听事件
        ListSelectionModel selectionModel = table.getSelectionModel();
        selectionModel.addListSelectionListener(new ListSelectionListener() {
            // 会响应两次，使用e.getValueIsAdjusting()判断，鼠标点击，getValueIsAdjusting() 返回True.
            // 鼠标释放,getValueIsAdjusting() 返回 False
            public void valueChanged(ListSelectionEvent e) {
                if (e.getValueIsAdjusting()) {
                    String str = e.getSource().toString();
                    // 取出当前行
                    String indexStr = str.substring(str.lastIndexOf("{") + 1, str.lastIndexOf("}"));
                    if (str != null && !"".equals(str.trim()) && indexStr != null && !"".equals(indexStr.trim())) {
                        // 获取当前行序号
                        int index = Integer.parseInt(indexStr);
                        Integer productsIds = (Integer) rowData[index][0];
                        Products productsServiceById = productsService.getById(productsIds);

                        if (productsServiceById == null) {
                            JOptionPane.showMessageDialog(null, "查找出错", "提示", JOptionPane.ERROR_MESSAGE);
                            return;
                        }
                        // 封装数据
                        productsId.setText(String.valueOf(productsServiceById.getProductid()));
                        productsName.setText(productsServiceById.getProductname());
                        productsNumber.setText(String.valueOf(productsServiceById.getQuantity()));


                    }
                }
            }
        });

    }

    /**
     * 更新供应商列表
     *
     * @param type  0 查找所有, 1 根据用户输入查找
     * @param input
     */
    private void updateProductsList(int type, String input) {
        productsService.getAllproducts();
        if (type == 0) rowData = productsService.getAllproducts();
        if (type == 1) rowData = productsService.getSearchProducts(input);
        table.updateModel(rowData, columnNames);
        clearField();
    }

    /**
     * 清空输入框数据
     */
    private void clearField() {
        productsId.setText("");
        productsName.setText("");
        productsNumber.setText("");

    }
}
